package com.demo.key.adap

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.recyclerview.widget.RecyclerView
import com.demo.key.R
import com.demo.key.server.ConnectServer0822Manager
import com.demo.key.server.Server0822Entity
import com.demo.key.server.ServerInfo0822Manager
import com.demo.key.util.serverFlagRes
import kotlinx.android.synthetic.main.layout_server_item.view.*

class Server0822Adapter(
    private val context:Context,
    private val clickItem:(en:Server0822Entity)->Unit
) :RecyclerView.Adapter<Server0822Adapter.MyView>(){
    private val list= arrayListOf<Server0822Entity>()
    init {
        list.add(ServerInfo0822Manager.createFastServer())
        list.addAll(ServerInfo0822Manager.getServerList())
    }

    inner class MyView (view:View):RecyclerView.ViewHolder(view){
        private val iv_connect_btn=view.findViewById<AppCompatImageView>(R.id.iv_connect_btn)
        init {
            iv_connect_btn.setOnClickListener {
                clickItem.invoke(list[layoutPosition])
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyView {
        return MyView(LayoutInflater.from(context).inflate(R.layout.layout_server_item,parent,false))
    }

    override fun onBindViewHolder(holder: MyView, position: Int) {
        with(holder.itemView){
            val server0822Entity = list[position]
            tv_server_name.text=server0822Entity.country_key0822
            iv_flag_icon.setImageResource(serverFlagRes(server0822Entity.country_key0822))

            val b = server0822Entity.host_key0822 == ConnectServer0822Manager.current.host_key0822
            iv_flag_bg.isSelected=b
            iv_connect_btn.isSelected=b

            tv_speed.text="${ServerInfo0822Manager.getServerSpeed(server0822Entity)} ms"
        }
    }

    override fun getItemCount(): Int = list.size

}